package dev

import (
	"os"
	"path/filepath"
)

var (
	rootDir *string
)

func RootDir(p ...string) string {
	root, _ := findGoModRoot()
	return filepath.Join(root, filepath.Join(p...))
}
func findGoModRoot() (string, error) {
	if rootDir != nil {
		return *rootDir, nil
	}
	dir, _ := os.Getwd()
	for {
		if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
			rootDir = &dir
			return dir, nil
		}
		parent := filepath.Dir(dir)
		if parent == dir {
			return "", os.ErrNotExist
		}
		dir = parent
	}
}
